'use strict';

import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import * as actions from '../../actions/ring_tags';
import Notice from 'qnui/lib/notice';
import Dialog from 'qnui/lib/dialog';
import Button from 'qnui/lib/button';
import Icon from 'qnui/lib/icon';
import Tag from 'qnui/lib/tag';
import Badge from 'qnui/lib/badge';
import Pagination from 'qnui/lib/pagination';
import { Row, Col } from 'qnui/lib/grid';
import { Loading,Tab } from 'qnui';
import MainNotice from 'components/main-notice/index';

import Tools from 'utils/index';
import linkConfig from 'utils/urls';
import './index.scss';
const links = Tools.isLocal() ? linkConfig.local : linkConfig.onLine;
import './index.scss';

class RingTags extends React.Component {
    constructor(props) {
        super(props);
		this.dispatch = this.props.dispatch;        
		this.state = {
			refreshDialog:false,
			refreshContent:"",
			currentPage:1,
			pageSize:10,
			choseDialog:false
        };
    }
	componentWillMount(){
		this.dispatch(
			actions.getTagTask({
				page:1,
				page_size:this.state.pageSize
			})
		);
	} 
	onPageChange(page){
		this.dispatch(
			actions.getTagTask({
				page:page,
				page_size:this.state.pageSize
			})
		);
	}
	handleEditTask(task){
		this.props.history.push({pathname:'/ring_tags_step1',state:task});
	}
	handleShowPromotions(task){
		if(task.promotion_count==0){
			this.setState({choseDialog:true,choseTask:task});
		}else{
			this.props.history.push({pathname:'/ring_zhekou_list',state:task});
		}
	}
	handleGo(type){
		switch(type){
			case "normal":
				this.props.history.push({pathname:'/ring_tags_step2?act_type=item',state:{...this.state.choseTask}});
				break;
			case "limit":
				this.props.history.push({pathname:'/ring_tags_step2?act_type=limit',state:{...this.state.choseTask}});
				break;
		}
		this.setState({choseDialog:false});
	}
	handleRunButton(text){
		Dialog.alert({"content":"当前标签的运行状况："+text+"。"});
	}
	handleCloseChoseDialog(){
		this.setState({choseDialog:false});
	}
	handleRemoveTask(task){
		if(task.promotion_count>0){
			Dialog.alert({content:"此活动下还有折扣，请先删除所有折扣，再删除本活动！"});
			return;
		}
		this.dispatch(actions.closeDialog());
		this.setState({removeTaskId:task.task_id,removeTask:true});
	}
	handleRemoveTaskOk(){
		this.dispatch(
			actions.removeTagTask(this.state.removeTaskId)
		);
		this.setState({removeTaskId:0,removeTask:false});
	}
	handleRemoveTaskCancel(){
		this.setState({removeTaskId:0,removeTask:false});
	}
	onRefreshClose(){
		this.setState({"refreshDialog":false});
	}
	onClose(){
		this.props.dispatch(actions.closeDialog());
	}
	
	tabChange(tab_id){
		switch(tab_id){
			case "countdown":	
				　window.location.href=links.ring_tags;
				break;
			case "limit_time":
				 window.location.href=links.zhekou1_list;
				break;
			case "mjs1":
				 window.location.href=links.mjs1_list;
				break;
			case "qrring":
				 window.location.href=links.qrring;
				break;
		}
	}
  render() {
	const tasks = this.props.ring_tags.data?this.props.ring_tags.data:[];
	const total = this.props.ring_tags.total;
	
	const loginBtn = this.props.ring_tags.loginError?
						<a href="https://oauth.taobao.com/authorize?response_type=code&client_id=21127968&redirect_uri=http://llxl.hz.taeapp.com/?state=ring_tags&view=web"><Button size="large" type="primary"><span>请重新登陆</span></Button></a>
					 :"";
    const footer = this.props.ring_tags.loginError?<div>{loginBtn}</div>:"";
	const creatingTitle = this.props.ring_tags.loading?"正在创建。。。":"错误信息";
	const creatingMsg = this.props.ring_tags.loading?<Loading />:this.props.ring_tags.message;
	const creatingDialog = this.props.ring_tags.loading?true:this.props.ring_tags.error;
	const cancleBtnText = this.state.editTag?"返回":"取消创建";
	const okBtnText = this.state.editTag?"修改":"创建活动";
	
	const extraContent = <Row>
								    <Button size="large" type="primary" component="a" href="http://www.alibaba.com" target="_blank">
								    <Icon type="pin" /><span>店内打折</span>
									</Button> &nbsp;&nbsp;
									<Button size="large" type="secondary" component="a" href="http://www.alibaba.com" target="_blank">
									    <span>推广打折</span>
									</Button>
								</Row>;
    return (<div className="ring-tags">
		<MainNotice />
		<Dialog
			visible={this.state.choseDialog}
			title="当前没有折扣，请创建："
			onClose={this.handleCloseChoseDialog.bind(this)}
			footer={false}
			>
			<Row>
					<Col span="12">
					<Button onClick={this.handleGo.bind(this,"normal")}>普通折扣</Button>
					</Col>
					<Col span="12" offset="2">
					<Button offset="2" onClick={this.handleGo.bind(this,"limit")}>限购折扣</Button>
					</Col>
			</Row>
		</Dialog>
		<Dialog
			title="删除活动"
			visible={this.state.removeTask}
			onOk = {this.handleRemoveTaskOk.bind(this)}
			onCancel = {this.handleRemoveTaskCancel.bind(this)}
			onClose = {this.handleRemoveTaskCancel.bind(this)} 
			>
			<div className="next-dialog-confirm">
				<div className="next-feedback next-feedback-help next-feedback-addon next-feedback-large next-feedback-title-content">
				<i className="next-icon next-icon-help next-icon-medium next-feedback-symbol"></i>
					<div className="next-feedback-title">
					您确定需要删除当前活动吗？
					</div>
				</div>
			</div>
		</Dialog>
		<Dialog
					visible = {this.state.refreshDialog}
                    onOk = {this.onRefreshClose.bind(this)}
                    onCancel = {this.onRefreshClose.bind(this)}
                    onClose = {this.onRefreshClose.bind(this)} 
					title = {this.state.refreshContent.title}
					style={{width:"445px",height:"360px"}}
					footer = {false}
					>
					<Row justify="center">
						{this.state.refreshContent.msg}
					</Row>
					<Row justify="center">
						{this.state.refreshContent.content}
					</Row>
            </Dialog>
			<Dialog style={{width:"600px"}} 
					visible = {creatingDialog}
                    onOk = {this.onClose.bind(this)}
                    onCancel = {this.onClose.bind(this)}
                    onClose = {this.onClose.bind(this)} 
					title = {creatingTitle}
					footer = {footer}
					>
					<Row justify="center">
						<h3>{creatingMsg}</h3>
					</Row>
            </Dialog>
			<Tab size="medium" type="wrapped" className="my-tab-bar" activeKey="qrring" tabBarExtraContent={extraContent}  style={{marginTop:"5px"}} onChange={this.tabChange.bind(this)}>
				<Tab.TabPane tab="付款倒计时折扣" key="countdown"></Tab.TabPane>
				<Tab.TabPane tab="二维码倒计时" key="qrring">
					<Row className="top5" type="wrap">
						{tasks.map((task,key)=>{
							let vaildText = "扫码获得";
								// switch(task.tag_family){
									// case "order":
										// task.item_count = 0;
										// vaildText =  "购买任意商品";
									// break;
									// case "item":
										// vaildText =  "购买指定商品";
									// break;
									// case "rate":
										// task.item_count = 0;
										// vaildText =  "好评";
									// break;
									// case "qrcode":
										// task.item_count = 0;
										// vaildText =  "扫码获得";
									// break;
								// }
							const isWatting = Date.parse(task.start_time)>Date.parse(new Date());
							const isEnd = Date.parse(task.end_time)<Date.parse(new Date());
							const isRuning = (!isWatting && !isEnd);
							let conuntdownText = <Tag shape="readonly" size="small">限时{task.countdown}分钟</Tag>;
							let runText = "";
							let runStyle = {backgroundColor:"none"};
							let btnType = "primary";
							let btnZheType = "secondary";
							let btnShape;
							if(isWatting){
								runText="在等待";
								runStyle = {backgroundColor:"#FAE7E7"};
								btnType = "normal";
								btnZheType = "normal";
								btnShape = "ghost";
							}
							if(isEnd){
								runText="已结束";
								runStyle = {backgroundColor:"#E6E6E6"};
								btnType = "normal";
								btnZheType = "normal";
								conuntdownText = <Tag shape="readonly" size="small">已停止</Tag>;
							}
							if(isRuning){
								runText="运行中";
							}
							return (
								<Col key={key} span="8" className="tag-task" style={{...runStyle,padding:"10px"}}>
									<Row justify="center" style={{marginBottom:"12px"}}>
										<Col>
										<h2>{task.tag_name}</h2>
										</Col>
										<Col fixedSpan="5" style={{lineHeight:"30px"}}>
										<Button  shape="text" onClick={this.handleRunButton.bind(this,runText)} type="light" size="small">{runText}</Button>&nbsp;
										<Link to={{pathname:"ring_runing_log",query:{id:task.tag_id}}} >
											<Button  shape="ghost" type="light" size="small">日志</Button>
										</Link>
										</Col>
										<div className="closeBtn" onClick={this.handleRemoveTask.bind(this,task)}>
										<Icon size="xs" type="close" />
										</div>
									</Row>
									<Row>
										<Col>
											<Row justify="center"><Tag shape="readonly" size="small">{vaildText}</Tag></Row>
											<Row justify="center">
												<Badge count={task.item_count}>
													<Button onClick={this.handleEditTask.bind(this,task)} type={btnType} shape={btnShape} size="large">规则设置</Button>
												</Badge>
											</Row>
										</Col>
										<Col>
											<Row justify="center">
											{conuntdownText}
											</Row>
											<Row justify="center">
												<Badge count={task.promotion_count}>
												<Button size="large" type={btnZheType} shape={btnShape} onClick={this.handleShowPromotions.bind(this,task)} ><Icon type="clock" />享受折扣</Button>
												</Badge>
											</Row>
										</Col>
									</Row>
								</Col>
							);
						})}
						<Col fixedSpan="8" className="add-btn">
							<Row className="top5 active-type info">
								<Link to="ring_tags_step1" style={{color:"#FFF",margin:"auto"}}>
								<Col span="4" align="center" className="icon iconfont">
									<Icon type="add" />
								</Col>
								</Link>
							</Row>
						</Col>
					</Row>
			</Tab.TabPane>
			
			{/*<Tab.TabPane tab="循环定时打折" key="daily_loop"></Tab.TabPane>
			<Tab.TabPane tab="付款打折" key="pay"></Tab.TabPane>*/}
			<Tab.TabPane tab="限时打折" key="limit_time"></Tab.TabPane>
			<Tab.TabPane tab="满打折/包邮" key="mjs1"></Tab.TabPane>
			<Tab.TabPane tab="限购优惠" key="limit_buy"></Tab.TabPane>
		</Tab>
        <Row  type="wrap" justify="end">
			<Pagination hideOnlyOnePage={true} onChange={this.onPageChange.bind(this)} defaultCurrent={1} pageSize={this.state.pageSize} total={parseInt(this.props.ring_tags.total)} type="mini" />
        </Row>
    </div>
	);
  }
}

export default connect((state)=> {
  return {
    ring_tags: state.ring_tags
  };
})(RingTags);
